/**
 *
 * @author John Creecy
 */

package server;

import server.entities.PlayerActionEntity;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class StateGenerator implements Runnable {

	public void run() {
		calculateState();
	}

	private void calculateState() {
		Iterator it = BattleBarn.actionStack.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry mapEntry = (Map.Entry) it.next();
			PlayerActionEntity playerActionEntity = (PlayerActionEntity) mapEntry.getValue();
			BattleBarn.gameState.add(playerActionEntity);
		}
		activityTracker();
	}

	private void activityTracker() {
		if(BattleBarn.packetsIn != BattleBarn.packetsInSnapshot) {
			sendState();
			BattleBarn.packetsInSnapshot = BattleBarn.packetsIn;
		} else {
			// no player activity this cycle
			BattleBarn.gameState.clear();
		}
	}

	private void sendState() {
		DatagramPacket sendPacket;
		for (int i = 0; i < BattleBarn.gameState.size(); i++) {
			try {
				Long timeStamp = (long) (System.currentTimeMillis());
				byte[] gameData = new byte[1024];
				DatagramSocket clientSocket = new DatagramSocket();
				PlayerActionEntity playerActionEntity = BattleBarn.gameState.get(i);

				//String ipAddress = playerActionEntity.getName().substring(1, playerActionEntity.getName().length());
				//String ipAddress = playerActionEntity.getName();
				String xPad = Integer.toString(playerActionEntity.getX());
				String yPad = Integer.toString(playerActionEntity.getY());

				switch(xPad.length()) {
					case 0: xPad = "000"; break;
					case 1: xPad = "00" + xPad; break;
					case 2: xPad = "0" + xPad; break;
				}
				switch(yPad.length()) {
					case 0: yPad = "000"; break;
					case 1: yPad = "00" + yPad; break;
					case 2: yPad = "0" + yPad; break;
				}
				String outData = playerActionEntity.getChatMessage();

				outData = timeStamp + xPad + yPad + playerActionEntity.getName();
				gameData = outData.getBytes();

				Iterator it = BattleBarn.clientList.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry mapEntry = (Map.Entry) it.next();
					InetAddress IPAddress = InetAddress.getByName((String) mapEntry.getKey());
					sendPacket = new DatagramPacket(gameData, gameData.length, IPAddress, 10000);
					clientSocket.send(sendPacket);
					BattleBarn.packetsOut++;
				}
			} catch (IOException ex) {
				Logger.getLogger(StateGenerator.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
		BattleBarn.gameState.clear();
	}
}
